package com.mjlf.mjatis.alias;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mjlf.mjatis.config.Configuration;
import lombok.Data;
import lombok.extern.java.Log;

import java.util.Collections;
import java.util.Set;

/**
 * @ClassName AliasParser
 * @Author mjlft
 * @Date 2020/5/28 23:44
 * @Version 1.0
 * @Description 别名解析器
 */
@Data
@Log
public class AliasParser {

    /**
     * 解析别名
     */
    public void parseConfig(JSONArray aliasArray, Configuration configuration){
        Set<Alias> aliases = AliasUtils.parse(aliasArray);
        mergeAlias(aliases, configuration);
    }

    public void parseConfig(JSONObject aliasJson, Configuration configuration){
        Alias alias = AliasUtils.parse(aliasJson);
        mergeAlias(Collections.EMPTY_SET, configuration);
        configuration.getAliases().add(alias);
    }

    public void parseConfig(String basePackagePath, Configuration configuration){
        Set<Alias> aliases = AliasUtils.parse(basePackagePath);
    }

    /**
     * 别名合并
     * @param aliases
     * @param configuration
     */
    private  void mergeAlias(Set<Alias> aliases, Configuration configuration){
        if(aliases == null)
            return;

        synchronized (configuration){
            if(configuration.getAliases() == null){
                configuration.setAliases(aliases);
            }else {
                configuration.getAliases().addAll(aliases);
            }
        }
    }

}
